/**   
 * @Title: IpGetter.java 
 * @Package com.esun.util.ip 
 * @Description: 获取本机ip 
 * @author: City Jiangsy@500wan.com   
 * @date: 2012-1-4 下午4:30:52  
 * Copyright: (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.util.ip;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import com.esun.util.log.EDebug;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

/**
 * @ClassName: IpGetter
 * @Description: 获取本机ip
 * @author: City Jiangsy@500wan.com
 * @date: 2012-1-4 下午4:30:52
 * 
 */
public class IpGetter {
	private Context context;
	private String strIp;
	private int intIp;

	public IpGetter(Context context) {
		this.context = context;
		strIp = "";
		intIp = -1;
		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		if (!wifiManager.isWifiEnabled()) {
			try {
				for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
					NetworkInterface intf = en.nextElement();
					for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
						InetAddress inetAddress = enumIpAddr.nextElement();
						if (!inetAddress.isLoopbackAddress()) {
							strIp = inetAddress.getHostAddress().toString();
						}
					}
				}
			} catch (SocketException ex) {
				EDebug.o(IpGetter.this, ex.toString());
			}
		} else {
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			intIp = wifiInfo.getIpAddress();
			strIp = intToIp(intIp);
		}
	}

	/**
	 * @return the strIp
	 */
	public String getStrIp() {
		return strIp;
	}

	/**
	 * @return the intIp
	 */
	public int getIntIp() {
		return intIp;
	}

	private String intToIp(int i) {
		// TODO Auto-generated method stub
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + (i >> 24 & 0xFF);
	}
}
